package com.bw.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bw.auth.exception.BizException;
import com.bw.auth.remote.AuthRemoteService;
import com.bw.auth.service.AuthService;
import com.bw.common.constants.JwtConstants;
import com.bw.common.constants.TokenConstants;
import com.bw.common.domain.User;
import com.bw.common.domain.request.JwtRequest;
import com.bw.common.result.Result;
import com.bw.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthRemoteService authRemoteService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JwtRequest login(User user) {

        String username = user.getUsername();
        String password = user.getPassword();

        Result<User> userResult = authRemoteService.selectUserInfo(username);
        User data = userResult.getData();

        if (data == null){
            throw new BizException("账号或密码不能为空");
        }

        if (!data.getPassword().equals(password)){
            throw new BizException("密码不正确");
        }

        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(data),60, TimeUnit.MINUTES);

        String token = JwtUtils.createToken(map);
        JwtRequest jwtRequest = new JwtRequest();
        jwtRequest.setToken(token);
        jwtRequest.setStrJwtTime("60MIN");
        jwtRequest.setRole(data.getRole());

        return jwtRequest;
    }
}
